package slideWindow;

import java.util.HashMap;
import java.util.Map;

/**
 * @author pengfei.hpf
 * @date 2020/2/22
 * @verdion 1.0.0
 */
public class LengthOfLongestSubstringTwoDistinct {

    public int lengthOfLongestSubstringTwoDistinct(String s){
        if(s == null || s.length() == 0){
            return 0;
        }
        int start = 0;
        Map<Character, Integer> map = new HashMap<>();
        char[] chars = s.toCharArray();
        int count = 0;
        int max = 0;
        for(int i = 0; i < chars.length; i++){
            count ++;
            if(!map.containsKey(chars[i]) && map.size() == 2){
                int smallStart = Integer.MAX_VALUE;
                int largeStart = 0;
                char toRemove = ' ';
                for(Map.Entry<Character, Integer> entry: map.entrySet()){

                    if(entry.getValue() < smallStart){
                        smallStart = entry.getValue();
                        toRemove = entry.getKey();
                    }
                    if(largeStart < entry.getValue()){
                        largeStart = entry.getValue();
                    }
                }
                map.remove(toRemove);

                count = count - (largeStart - start);
                start = largeStart;
                map.put(chars[i], i);
            } else if(!map.containsKey(chars[i]) || map.containsKey(chars[i]) && chars[i] != chars[i - 1]){
                map.put(chars[i], i);
            }
            if(count > max){
                max = count;
            }
        }
        return count;
    }
}
